<?php

namespace common\modules\wechat\controllers\backend;

use common\modules\wechat\models\backend\Account;
use common\modules\wechat\models\backend\AccountForm;
use common\modules\wechat\models\backend\AccountSearch;
use common\modules\wechat\components\AdminController;
use common\widgets\pages\GridViewPage;
use Yii;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii\web\NotFoundHttpException;

/**
 * 微信公众号管理
 *
 * @package common\modules\wechat\controllers\backend
 */
class AccountController extends AdminController
{
    /**
     * 关闭公众号设置检查
     *
     * @var bool
     */
    public $enableCheckWechat = false;

    /**
     * 显示所有公众号
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AccountSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());

        $page = $this->createGridViewPage($dataProvider, $searchModel);
        return $page->render([
            GridViewPage::GRID_VIEW_CONFIG => [
                'rowOptions' => function ($model) {
                    if ($model->id == Yii::$app->session->get(self::SESSION_MANAGE_WECHAT_KEY))
                    {
                        return [
                            'class' => 'success',
                        ];
                    }
                    return [];
                },
            ],
        ]);
    }

    /**
     * 设置当前管理的公众号
     *
     * @param $id
     * @return Response
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionManage($id)
    {
        $model = $this->findModel($id);

        if ($this->setWechat($model))
        {
            return $this->flash('success', '当前管理公众号设置为"' . $model->name . '", 您现在可以管理该公众号了', ['index']);
        }
        else
        {
            return $this->flash('error', '公众号无法选择!', ['index']);
        }
    }

    /**
     * Creates a new Item model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new AccountForm(['scenario' => AccountForm::SCENARIO_CREATE]);

        $model->isNewRecord = true;

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    return $this->flash('info', '公众号创建成功! 请补充余下公众号设置以激活公众号', ['update', 'id' => $model->id]);
                }
                else
                {
                    Yii::$app->session->setFlash('danger', '创建失败!');
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            AccountForm::SCENARIO_CREATE,
            [
                'pageTitle' => Yii::t('backend/wechat', 'Create Wechat Account'),
            ]
        );
        return $page->render();
    }

    /**
     * 修改公众号信息
     *
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario(AccountForm::SCENARIO_UPDATE);

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    Yii::$app->session->setFlash('success', '更新成功!');
                }
                else
                {
                    Yii::$app->session->setFlash('danger', '更新失败');
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            AccountForm::SCENARIO_UPDATE,
            [
                'pageTitle' => Yii::t('backend/wechat', 'Update Wechat Account'),
            ]
        );
        return $page->render();
    }

    /**
     * 删除公众号
     *
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Wechat model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     * @return Account the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AccountForm::findOne($id)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
